<template>
  <div class="idea-page">
    <!-- 右上角AI助手按钮 -->
    <div class="ai-btn" @click="goAI">
      <van-icon name="smile-comment-o" />
      <span>问问AI助手</span>
    </div>
    <!-- 头部用户信息 -->
    <div class="user-header">
      <img class="avatar" :src="userAvatar" @click="goUserOrLogin" />
      <div class="user-info" @click="goUserOrLogin" style="cursor:pointer;">
        <div class="username">{{ userName }}</div>
        <div class="date">{{ currentDate }}</div>
      </div>
    </div>
    <!-- 卡路里目标 -->
    <div class="target-section">
      <div class="target-title">
        <van-icon name="fire-o" style="color:#ff8000;font-size:24px;vertical-align:middle;" />
        <span style="margin-left:8px;">卡路里目标</span>
        <span class="target-type" @click="showCalorieDialog">每周 <van-icon name="arrow-down" /></span>
      </div>
      <div class="target-value">{{ calorieGoal }} <span class="unit">千卡</span></div>
    </div>
    <!-- 柱状图 -->
    <div ref="chartRef" class="bar-chart"></div>
    <!-- 数据卡片 -->
    <div class="data-card">
      <div class="data-header">本周营养摄入</div>
      <div class="data-content">
        <div class="data-item">
          <img src="/src/assets/images/protein.png" class="carbon-water">
          <div class="data-value">{{ formatNumber(nutritionData.protein) }}克</div>
          <div class="data-label">蛋白质</div>
        </div>
        <div class="data-item">
          <img src="/src/assets/images/carbs.png" class="carbon-water">
          <div class="data-value">{{ formatNumber(nutritionData.carbs) }}克</div>
          <div class="data-label">碳水化合物</div>
        </div>
        <div class="data-item">
          <van-icon name="fire-o" size="30" />
          <div class="data-value">{{ formatNumber(nutritionData.fat) }}克</div>
          <div class="data-label">脂肪</div>
        </div>
      </div>
    </div>
    
    <!-- 添加卡路里目标设置弹窗 -->
    <van-dialog
      v-model:show="showCalorieSetting"
      title="设置每周卡路里目标"
      show-cancel-button
      @confirm="updateCalorieGoal"
    >
      <div class="calorie-setting">
        <van-field
          v-model="newCalorieGoal"
          type="number"
          label="目标卡路里"
          placeholder="请输入目标卡路里"
        >
          <template #button>
            <span class="unit">千卡</span>
          </template>
        </van-field>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { db, STORES } from '../utils/db'
import { showToast } from 'vant'
import { getWeeklyNutrition, getCalorieGoal } from '../utils/nutritionSync'

const router = useRouter()
const goAI = () => {
  router.push({ name: 'ai' })
}

const chartRef = ref(null)
let chart = null
let nutritionTimer = null

const currentDate = ref('')

const updateDate = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  currentDate.value = `${year}.${month}.${day}`
}

let timer = null

const DEFAULT_AVATAR = 'https://img.yzcdn.cn/vant/cat.jpeg'
const userName = ref('请登录')
const userAvatar = ref(DEFAULT_AVATAR)
const goUserOrLogin = () => {
  if (!localStorage.getItem('isLogin')) {
    router.push('/login')
  } else {
    router.push('/user')
  }
}

// 添加响应式数据
const nutritionData = ref({
  protein: 0,
  carbs: 0,
  fat: 0
})
const calorieGoal = ref(2000)

// 添加数字格式化函数
const formatNumber = (num) => {
  if (typeof num !== 'number') return '0'
  return Math.round(num).toString()
}

// 加载营养数据
const loadNutritionData = async () => {
  const userEmail = localStorage.getItem('userEmail')
  if (!userEmail) return

  try {
    const { weekData, weekTotal } = await getWeeklyNutrition(userEmail)
    const goal = await getCalorieGoal(userEmail)
    
    // 更新卡路里目标
    calorieGoal.value = goal

    // 更新图表数据
    if (chart) {
      const today = new Date().getDay()
      const chartData = weekData.map(day => ({
        value: day.calories,
        itemStyle: {
          color: day.date === today ? {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: '#ff9f43'
            }, {
              offset: 1,
              color: '#ff8000'
            }]
          } : {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: '#f0f0f0'
            }, {
              offset: 1,
              color: '#e0e0e0'
            }]
          }
        }
      }))

      chart.setOption({
        series: [{
          data: chartData
        }]
      })
    }

    // 更新数据卡片为本周总和
    nutritionData.value = {
      protein: weekTotal.protein,
      carbs: weekTotal.carbs,
      fat: weekTotal.fat
    }
  } catch (error) {
    console.error('加载营养数据失败:', error)
    showToast('加载数据失败')
  }
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  
  chart = echarts.init(chartRef.value)
  chart.setOption({
    grid: { 
      left: 40, 
      right: 40, 
      top: 50, 
      bottom: 20, 
      containLabel: true 
    },
    xAxis: {
      type: 'category',
      data: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
      axisTick: { show: false },
      axisLine: { 
        show: true,
        lineStyle: {
          color: '#e0e0e0'
        }
      },
      axisLabel: { 
        color: '#666', 
        fontSize: 14,
        fontWeight: 500,
        margin: 12
      }
    },
    yAxis: { 
      show: true,
      type: 'value',
      splitLine: {
        show: true,
        lineStyle: {
          color: '#f5f5f5',
          type: 'dashed'
        }
      },
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: {
        show: true,
        color: '#999',
        fontSize: 11,
        formatter: '{value}'
      }
    },
    series: [
      {
        type: 'bar',
        data: Array(7).fill(0).map((_, index) => ({
          value: 0,
          itemStyle: {
            color: index === new Date().getDay() ? {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: '#ff9f43'
              }, {
                offset: 1,
                color: '#ff8000'
              }]
            } : {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: '#f0f0f0'
              }, {
                offset: 1,
                color: '#e0e0e0'
              }]
            }
          }
        })),
        barWidth: 24,
        barCategoryGap: '40%',
        label: {
          show: false
        },
        emphasis: {
          itemStyle: {
            shadowColor: 'rgba(255, 128, 0, 0.3)',
            shadowBlur: 8
          }
        }
      }
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c} 大卡',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#ff8000',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      padding: [8, 12]
    }
  })
}

// 监听数据库变化
const setupDBListener = () => {
  const userEmail = localStorage.getItem('userEmail')
  if (!userEmail) return

  // 每10秒刷新一次数据
  return setInterval(loadNutritionData, 10000)
}

// 添加卡路里目标设置相关
const showCalorieDialog = () => {
  if (!localStorage.getItem('isLogin')) {
    showToast('请先登录')
    router.push('/login')
    return
  }
  newCalorieGoal.value = calorieGoal.value
  showCalorieSetting.value = true
}

const showCalorieSetting = ref(false)
const newCalorieGoal = ref(2000)

const updateCalorieGoal = async () => {
  const userEmail = localStorage.getItem('userEmail')
  if (!userEmail) return

  try {
    await db.put(STORES.CALORIE_GOAL, {
      userEmail: userEmail,
      target: newCalorieGoal.value
    })
    calorieGoal.value = newCalorieGoal.value
    showCalorieSetting.value = false
    showToast('设置成功')
  } catch (error) {
    console.error('更新卡路里目标失败:', error)
    showToast('设置失败')
  }
}

onMounted(async () => {
  updateDate()
  if (localStorage.getItem('isLogin')) {
    try {
      const userEmail = localStorage.getItem('userEmail')
      if (userEmail) {
        const user = await db.get(STORES.USER_LIST, userEmail)
        if (user) {
          userName.value = user.username || '测试用户'
          userAvatar.value = user.avatar || DEFAULT_AVATAR
        }
      }
      
      const storedUserName = localStorage.getItem('userName')
      userName.value = storedUserName || '测试用户'
    } catch (error) {
      console.error('获取用户信息失败:', error)
      showToast('获取用户信息失败')
    }
  } else {
    userName.value = '请登录'
    userAvatar.value = DEFAULT_AVATAR
  }
  
  timer = setInterval(updateDate, 24 * 60 * 60 * 1000)
  
  // 等待 DOM 更新后初始化图表和数据
  await nextTick()
  initChart()
  await loadNutritionData()
  nutritionTimer = setupDBListener()
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
  if (chart) {
    chart.dispose()
  }
  if (nutritionTimer) {
    clearInterval(nutritionTimer)
  }
})
</script>

<style scoped>
/* 添加全局样式 */
:deep(body) {
  overflow: hidden;
  position: fixed;
  width: 100%;
  height: 100%;
  touch-action: manipulation;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  user-select: none;
  -webkit-tap-highlight-color: transparent;
}

/* 禁用双击缩放 */
:deep(*) {
  touch-action: manipulation;
  -webkit-text-size-adjust: none;
  -moz-text-size-adjust: none;
  -ms-text-size-adjust: none;
  text-size-adjust: none;
}

.carbon-water{
  width:30px;
  height:30px;
}

.idea-page {
  min-height: 100vh;
  height: 100vh;
  background: linear-gradient(135deg, #e9eafc 0%, #e6e6fa 100%);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  padding-bottom: 24px;
  overflow: hidden;
  z-index: 1;
}

.ai-btn {
  position: absolute;
  top: 16px;
  right: 20px;
  background: #7062c1;
  color: #fff;
  border-radius: 20px;
  padding: 6px 16px 6px 12px;
  font-size: 15px;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 12px rgba(112, 98, 193, 0.2);
  z-index: 10;
  cursor: pointer;
  transition: all 0.3s ease;
}

.ai-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(112, 98, 193, 0.3);
}

.ai-btn .van-icon {
  font-size: 20px;
  margin-right: 6px;
}
.user-header {
  display: flex;
  align-items: center;
  padding: 18px 16px 8px 16px;
  background: transparent;
  position: relative;
}
.avatar {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  margin-right: 12px;
  border: 2px solid #fff;
  box-shadow: 0 2px 8px #e0e0e0;
}
.user-info {
  flex: 1;
}
.username {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}
.date {
  font-size: 13px;
  color: #aaa;
}
.target-section {
  padding: 0 20px;
  margin-bottom: 16px;
}

.target-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  color: #ff8000;
  margin-bottom: 8px;
}

.target-type {
  font-size: 14px;
  color: #888;
  margin-left: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
}

.target-value {
  font-size: 42px;
  font-weight: bold;
  color: #ff8000;
  line-height: 1.1;
}

.unit {
  font-size: 18px;
  color: #888;
  margin-left: 4px;
}

.bar-chart {
  width: calc(100% - 40px);
  height: 240px;
  margin: 0 auto 20px auto;
  background: #fff;
  border-radius: 24px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  padding: 20px 0 0 0;
}

.data-card {
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #6ed18a 0%, #5bc17a 100%);
  border-radius: 24px;
  margin: 0 20px;
  padding: 16px 0 16px 0;
  box-shadow: 0 4px 16px rgba(110, 209, 138, 0.2);
}

.data-header {
  text-align: center;
  color: #fff;
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 12px;
  font-weight: 500;
}

.data-content {
  display: flex;
  justify-content: space-around;
}

.data-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  color: #fff;
}

.data-value {
  font-size: 20px;
  font-weight: bold;
  margin: 8px 0 4px 0;
}

.data-label {
  font-size: 14px;
  opacity: 0.9;
}

.data-item:not(:last-child) {
  border-right: 1px solid rgba(255, 255, 255, 0.2);
}

.calorie-setting {
  padding: 16px;
}

.calorie-setting .unit {
  color: #666;
  margin-left: 8px;
}

:deep(.van-dialog) {
  border-radius: 24px;
  overflow: hidden;
}

:deep(.van-dialog__header) {
  padding: 24px 24px 16px;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

:deep(.van-dialog__content) {
  padding: 16px 24px 24px;
}

:deep(.van-field) {
  background: #f8f9ff;
  border-radius: 12px;
  padding: 12px 16px;
}

:deep(.van-field__label) {
  color: #666;
  font-weight: 500;
}

:deep(.van-field__control) {
  color: #333;
  font-size: 15px;
}

:deep(.van-dialog__footer) {
  padding: 16px 24px 24px;
}

:deep(.van-dialog__button) {
  font-size: 16px;
  font-weight: 600;
  height: 44px;
  border-radius: 22px;
}

:deep(.van-dialog__confirm) {
  background: linear-gradient(135deg, #7c5dfa 0%, #7062c1 100%);
  border: none;
  color: #fff;
}

:deep(.van-dialog__cancel) {
  color: #666;
  border: 1px solid #ddd;
}
</style>